package com.wonder.taxi.base;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import com.wonder.db.DbConnectionPoolFactory;


public class BaseService
{
    public Response buildResponse(Object p_result, String p_mimeType, java.util.Date p_expires)
    {
        ResponseBuilder builder = Response.ok(p_result, p_mimeType);
        if (p_expires != null)
        {
            builder.expires(p_expires);
        }
        return builder.build();
    }

    public PreparedStatement createSqlStatement(String p_sql, Object... p_parameters)
            throws Exception
    {
        Connection connection = DbConnectionPoolFactory.getInstance().getConnection();
        PreparedStatement statement = connection.prepareStatement(p_sql);
        for (int i = 0; i < p_parameters.length; i++)
        {
            Object param = p_parameters[i];
            statement.setObject(i + 1, param);
        }
        return statement;
    }

    public CallableStatement createCallStatement(String p_sql, Object... p_parameters)
            throws Exception
    {
        Connection connection = DbConnectionPoolFactory.getInstance().getConnection();
        CallableStatement statement = connection.prepareCall(p_sql);
        for (int i = 0; i < p_parameters.length; i++)
        {
            Object param = p_parameters[i];
            statement.setObject(i + 1, param);
        }
        return statement;
    }

    public CallableStatement executeCallStatement(String p_sql, Object... p_parameters)
            throws Exception
    {
        CallableStatement statement = createCallStatement(p_sql, p_parameters);
        statement.execute();
        return statement;
    }

    public ResultSet executeSql(String p_sql, Object... p_parameters) throws Exception
    {
        PreparedStatement statement = createSqlStatement(p_sql, p_parameters);
        statement.execute();
        return statement.getResultSet();
    }

    public Connection executeSqlWithoutResultSet(String p_sql, Object... p_parameters)
            throws Exception
    {
        PreparedStatement statement = createSqlStatement(p_sql, p_parameters);
        statement.execute();
        return statement.getConnection();
    }
    
	public static void writeLine(String fileName, String line)
	{
		try{
			BufferedWriter fileWriter = new BufferedWriter(
					new FileWriter(new File(fileName), true));
			fileWriter.write(line);
			fileWriter.newLine();
			fileWriter.flush();
			fileWriter.close();
		}catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
}